<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use EasyWeChat\Foundation\Application;

class weChatController extends Controller
{
  // 验证
  public function index(Request $request)
  {
    $options = [
      'debug'  => true,
      'app_id' =>  env('WECHAT_APP_ID'),
      'secret' =>  env('WECHAT_APP_SECRET'),
      'token'  =>  env('WECHAT_APP_TOKEN'),
      'aes_key' => env('WECHAT_APP_AES_KEY'), // 可选
      'log' => [
        'level' => 'debug',
        'file'  => '/var/www/wechat/storage/logs/wechat.log',
      ],
    ];
    $app = new Application($options);
    $userService = $app->user;

    $app->server->setMessageHandler(function ($message) use ($userService) {
      $openid = $message->FromUserName; // 用户的 openid
      if ( $message->Event == 'subscribe' ) {
        dispatch(new \App\Jobs\SendWechatEmail("有人关注你了，，，恭喜！！！关注者：".$openid));
        return '欢迎关注本微信公众号';
      }

      $content = '消息内容';
      if ( $message->MsgType == 'text' ) {
        $content =  $message->Content;
      } elseif ( $message->MsgType == 'image' ) {
        $content = $message->PicUrl;
      }
      dispatch(new \App\Jobs\SendWechatEmail("有人发消息了，内容：".$content));
      // $aa =  $userService->get('otKbvwg8DQbkN1zDbrrtCxvXAw5s');  权限不够，fuck了
      return $openid . "您好！欢迎关注我!"."，你的消息类型为：".$message->MsgType."，内容：".$content;
    });

    $response = $app->server->serve();
    // 将响应输出
    return $response;
  }
}
